<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <template slot="before">当前共有{{ total }}条记录</template>
        <template slot="after">
          <el-button type="warning" size="mini" @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button type="danger" size="mini">导出</el-button>
          <el-button type="primary" size="mini" @click="showDialog = true" v-if="checkPermission('POINT-USER-ADD')"
            >新增员工</el-button
          >
        </template>
      </page-tools>
      <el-card v-loading="loading">
        <el-table
          :data="tableData"
          style="width: 100%"
          :default-sort="{ prop: 'timeOfEntry', order: 'descending' }"
          border
        >
          <el-table-column
            prop="date"
            label="序号"
            sortable
            width="80"
            align="center"
            type="index"
          />
          <el-table-column
            prop="username"
            label="姓名"
            sortable
            width="150"
            align="center"
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            sortable
            align="center"
          />
          <el-table-column
            prop="workNumber"
            label="头像"
            align="center"
            width="120"
          >
            <template slot-scope="scope">
              <img
                :src="scope.row.staffPhoto"
                alt=""
                style="width: 100%"
                @click="qrcode(scope.row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable
            align="center"
            :formatter="formatterEmployment"
          />
          <el-table-column
            prop="departmentName"
            label="部门"
            sortable
            align="center"
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            sortable
            width="220"
            align="center"
          />
          <el-table-column
            prop="enableState"
            label="账户状态"
            sortable
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="date"
            label="操作"
            sortable
            width="300"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                @click="$router.push(`employees/detail/${scope.row.id}`)"
                :disabled="!checkPermission('POINT-USER-UPDATE')"
                >查看</el-button
              >
              <el-button type="text" size="mini">转正</el-button>
              <el-button type="text" size="mini">调岗</el-button>
              <el-button type="text" size="mini">离职</el-button>
              <el-button type="text" size="mini" @click="role(scope.row.id)" :disabled="!checkPermission('POINT-USER-UPDATE')">角色</el-button>
              <el-button
                type="text"
                size="mini"
                @click="delEmployee(scope.row.id)"
                :disabled="!checkPermission('point-user-delete')"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px; display: flex; justify-content: end">
          <el-pagination
          @size-change="fetchData()"
          @current-change="fetchData()"
          :current-page.sync="page.page"
          :page-sizes="[10, 50, 100]"
          :page-size.sync="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
        </div>
      </el-card>
      <!-- 新增员工的弹层 -->
      <!-- 使用组件 -->
      <!-- 这里为什么可以用sync 因为后面的变量是来源于data -->
      <!-- 子组件 this.$emit("update:showDialog", false) -->
      <add-employee :show-dialog.sync="showDialog" />
      <!-- 图片二维码的弹出层      -->
      <el-dialog title="头像二维码" :visible.sync="cdoeVisible" width="30%">
        <canvas ref="myCanvas" />
      </el-dialog>

      <!-- 角色的弹出层 -->
      <add-role :show-role-dialog.sync="showRoleDialog"  ref="addRole" :userId="userId"/>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee} from "@/api/employees";
import { getTime } from "@/utils/index";
import EmployeeEnum from "@/api/constant/employees";
import addEmployee from "./components/addEmployee.vue";
import addRole from "./components/addRole.vue";
import QrCode from "qrcode";
export default {
  components: { addEmployee,addRole },
  data() {
    return {
      showDialog: false,
      showRoleDialog:false,
      tableData: [],
      userId:"",
      page: {
        page: 1,
        size: 10,
      },
      total: 10,
      loading: false,
      cdoeVisible: false,
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取员工列表综合信息
    async fetchData() {
      this.loading = true;
      // const res = await getEmployeeList(this.params) // 有{total:26,rows:[]}
      // 为了方便我这里直接解构，写法更快,下次取值的时候就不用total=res.total 很麻烦
      const { total, rows } = await getEmployeeList(this.page);
      for (const time of rows) {
        if (time.timeOfEntry) time.timeOfEntry = getTime(time.timeOfEntry); // 处理时间，把时间转为标准格式
      }
      this.tableData = rows;
      console.log(this.tableData);
      this.total = total;
      this.loading = false;
      // console.log(total, rows)
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm("确定删除员工信息吗？");
        await delEmployee(id);
        this.$message.success("删除成功");
        this.fetchData();
      } catch (error) {
        console.log(error);
      }

      // await delEmployee(id)
      console.log(id);
    },

    // 格式化聘用形式
    formatterEmployment(row, column, cellValue) {
      // cellValue是表格当前的数据 如我表格当前的数据是 1和2 或者是什么都没有
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue);
      // console.log('格式', obj) // 能找到 或者找不到（undefined）
      // console.log(row, column, cellValue)
      return obj ? obj.value : "未知";
    },
    // 生成二维码
    qrcode(url) {
      this.cdoeVisible = true;
      // 等先生成节点
      this.$nextTick(() => {
       QrCode.toCanvas(this.$refs.myCanvas, url)
      });

    },
    async role(id){
      /*
      props传值是异步的，所以不能在子组件里面 created里面获取数据;
      因为一进去页面我的子组件还没有获取到父组件传过来的id，所以此时发请求
      会造成传入的参数是空
      正确做法：传入id之后才调用子组件
      */
      this.userId=id
      await this.$refs.addRole.getUserDetailById(id)
      this.showRoleDialog=true
    }

    
  },
};
</script>

<style lang="scss">

</style>
